<script setup lang="ts">
import type { Banner, Category, Product } from '@/types/mall'
import { formatPrice } from '@/utils/mall'

const router = useRouter()
const cartStore = useCartStore()

// 轮播图数据
const banners = ref<Banner[]>([
  {
    id: '1',
    title: '新品上市',
    image: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-15-pro-max-naturaltitanium-pdp-image-position-1a_CN.jpg',
    link: '/subPackages/product-package/goodsDetail/index?id=1',
    linkType: 'product',
    sort: 1,
    status: 'active',
  },
  {
    id: '2',
    title: '限时优惠',
    image: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/macbook-air-13-m3-midnight-pdp-image-position-1_CN.jpg',
    link: '/subPackages/product-package/goodsDetail/index?id=2',
    linkType: 'product',
    sort: 2,
    status: 'active',
  },
])

// 商品分类数据
const categories = ref<Category[]>([
  { id: '1', name: '手机数码', icon: 'phone', level: 1, sort: 1 },
  { id: '2', name: '电脑办公', icon: 'laptop', level: 1, sort: 2 },
  { id: '3', name: '家用电器', icon: 'tv', level: 1, sort: 3 },
  { id: '4', name: '服饰内衣', icon: 'shirt', level: 1, sort: 4 },
  { id: '5', name: '鞋靴箱包', icon: 'shoe', level: 1, sort: 5 },
  { id: '6', name: '运动户外', icon: 'basketball', level: 1, sort: 6 },
  { id: '7', name: '美妆护肤', icon: 'star', level: 1, sort: 7 },
  { id: '8', name: '母婴用品', icon: 'baby', level: 1, sort: 8 },
])

// 热门商品数据
const hotProducts = ref<Product[]>([
  {
    id: '1',
    name: 'iPhone 15 Pro Max',
    description: '全新iPhone 15 Pro Max，搭载A17 Pro芯片',
    categoryId: '1',
    images: ['https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-15-pro-max-naturaltitanium-pdp-image-position-1a_CN.jpg'],
    defaultPrice: 999900,
    originalPrice: 1099900,
    sales: 1200,
    stock: 50,
    status: 'active',
    rating: 4.8,
    reviewCount: 520,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  },
  {
    id: '2',
    name: 'MacBook Air 13英寸',
    description: 'M3芯片，轻薄便携，续航持久',
    categoryId: '2',
    images: ['https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/macbook-air-13-m3-midnight-pdp-image-position-1_CN.jpg'],
    defaultPrice: 899900,
    originalPrice: 999900,
    sales: 850,
    stock: 30,
    status: 'active',
    rating: 4.9,
    reviewCount: 326,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  },
  {
    id: '3',
    name: 'iPad Pro 12.9英寸',
    description: 'M2芯片，Liquid Retina XDR显示屏',
    categoryId: '1',
    images: ['https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/ipad-pro-12-9-6th-gen-wifi-select-spacegray_FMT_WHH.jpg'],
    defaultPrice: 899900,
    originalPrice: 999900,
    sales: 620,
    stock: 25,
    status: 'active',
    rating: 4.7,
    reviewCount: 284,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  },
  {
    id: '4',
    name: 'Apple Watch Series 9',
    description: '健康守护，智能体验，全天候监测',
    categoryId: '1',
    images: ['https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/watch-s9-45mm-pink-sport-band_FM.jpg'],
    defaultPrice: 299900,
    originalPrice: 349900,
    sales: 1580,
    stock: 60,
    status: 'active',
    rating: 4.6,
    reviewCount: 892,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  },
])

// 推荐商品数据
const recommendProducts = ref<Product[]>([
  {
    id: '5',
    name: 'AirPods Pro 第二代',
    description: '主动降噪，空间音频，无线充电',
    categoryId: '1',
    images: ['https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/airpods-pro-2nd-gen_FMT_WHH.jpg'],
    defaultPrice: 189900,
    originalPrice: 199900,
    sales: 2100,
    stock: 80,
    status: 'active',
    rating: 4.8,
    reviewCount: 1205,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  },
  {
    id: '6',
    name: 'Magic Keyboard',
    description: 'iPad Pro专用键盘，触控板设计',
    categoryId: '2',
    images: ['https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/magic-keyboard-ipad-pro-12-9-6th-gen-black_FMT_WHH.jpg'],
    defaultPrice: 249900,
    originalPrice: 279900,
    sales: 450,
    stock: 35,
    status: 'active',
    rating: 4.5,
    reviewCount: 186,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  },
  {
    id: '7',
    name: 'Studio Display',
    description: '27英寸5K Retina显示器',
    categoryId: '2',
    images: ['https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/studio-display_FMT_WHH.jpg'],
    defaultPrice: 1159900,
    originalPrice: 1199900,
    sales: 120,
    stock: 15,
    status: 'active',
    rating: 4.7,
    reviewCount: 95,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  },
  {
    id: '8',
    name: 'Mac Studio',
    description: 'M2 Max芯片，专业级台式机',
    categoryId: '2',
    images: ['https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/mac-studio_FMT_WHH.jpg'],
    defaultPrice: 1999900,
    originalPrice: 2199900,
    sales: 85,
    stock: 12,
    status: 'active',
    rating: 4.9,
    reviewCount: 52,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  },
  {
    id: '9',
    name: 'iPhone 15',
    description: '动态岛设计，A16仿生芯片',
    categoryId: '1',
    images: ['https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-15-pink-select_FMT_WHH.jpg'],
    defaultPrice: 599900,
    originalPrice: 649900,
    sales: 1850,
    stock: 45,
    status: 'active',
    rating: 4.6,
    reviewCount: 824,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  },
  {
    id: '10',
    name: 'MacBook Pro 14英寸',
    description: 'M3 Pro芯片，专业级性能',
    categoryId: '2',
    images: ['https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/macbook-pro-14-m3-pro-spacegray_FMT_WHH.jpg'],
    defaultPrice: 1599900,
    originalPrice: 1699900,
    sales: 420,
    stock: 28,
    status: 'active',
    rating: 4.8,
    reviewCount: 235,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  },
])

// 搜索关键词
const searchKeyword = ref('')

// 限时抢购商品
const flashSaleProducts = ref([
  {
    id: '11',
    name: 'iPhone 15 Pro',
    image: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-15-pro-naturaltitanium-pdp-image-position-1a_CN.jpg',
    currentPrice: 799900,
    originalPrice: 899900,
    discount: 11
  },
  {
    id: '12',
    name: 'iPad Air',
    image: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/ipad-air-11-m2-wifi-blue_FMT_WHH.jpg',
    currentPrice: 459900,
    originalPrice: 499900,
    discount: 8
  },
  {
    id: '13',
    name: 'AirPods 3',
    image: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/airpods-3rd-gen_FMT_WHH.jpg',
    currentPrice: 139900,
    originalPrice: 169900,
    discount: 18
  },
  {
    id: '14',
    name: 'Apple TV 4K',
    image: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/apple-tv-4k-hero-select_FMT_WHH.jpg',
    currentPrice: 119900,
    originalPrice: 149900,
    discount: 20
  }
])

// 页面跳转方法
function navigateTo(path: string) {
  uni.navigateTo({ url: path })
}

// 跳转到商品详情
function goToProductDetail(productId: string) {
  navigateTo(`/subPackages/product-package/goodsDetail/index?id=${productId}`)
}

// 跳转到分类页面
function goToCategory(categoryId: string) {
  uni.redirectTo({ 
    url: `/pages/category/index?id=${categoryId}`,
    success: () => {
      console.log('Navigate to category:', categoryId)
    },
    fail: (err) => {
      console.error('Navigation failed:', err)
    }
  })
}

// 跳转到游戏中心
function goToGameCenter() {
  navigateTo('/subPackages/game-package/list/index')
}

// 跳转到优惠券中心
function goToCouponCenter() {
  navigateTo('/subPackages/user-package/coupon/index')
}

// 跳转到限时抢购
function goToFlashSale() {
  uni.navigateTo({ url: '/subPackages/product-package/flash-sale/index' })
}

// 跳转到会员专享
function goToVipCenter() {
  uni.showToast({ title: '功能开发中...', icon: 'none' })
}

// 跳转到搜索页面
function goToSearch() {
  if (searchKeyword.value.trim()) {
    navigateTo(`/subPackages/product-package/search/index?keyword=${encodeURIComponent(searchKeyword.value.trim())}`)
  } else {
    navigateTo('/subPackages/product-package/search/index')
  }
}

// 跳转到消息中心
function goToMessage() {
  uni.showToast({ title: '功能开发中...', icon: 'none' })
}

// 扫一扫功能
function openScan() {
  uni.showToast({ title: '扫一扫功能开发中...', icon: 'none' })
}

// 跳转到积分商城
function goToPointsMall() {
  uni.navigateTo({ url: '/subPackages/user-package/points-mall/index' })
}

// 添加到购物车
async function addToCart(product: Product) {
  try {
    const success = await (cartStore as any).addToCart(product)
    if (success) {
      uni.vibrateShort()
    }
  } catch (error) {
    console.error('添加到购物车失败:', error)
    uni.showToast({ title: '添加到购物车失败', icon: 'none' })
  }
}

// 生命周期
onMounted(async () => {
  try {
    await (cartStore as any).initCart()
  } catch (error) {
    console.error('初始化购物车失败:', error)
  }
})
</script>

<template>
  <view class="min-h-screen bg-gradient-to-b from-blue-50 to-gray-50">
    <!-- 顶部状态栏 -->
    <view class="bg-gradient-to-r from-blue-500 to-purple-600 text-white px-4 py-2">
      <view class="flex items-center justify-between">
        <view class="flex items-center gap-2">
          <wd-icon name="location" size="14px" color="white" />
          <text class="text-12px opacity-90">北京市朝阳区</text>
        </view>
        <view class="flex items-center gap-3">
          <view class="flex items-center gap-1" @click="goToMessage">
            <wd-icon name="message" size="14px" color="white" />
            <text class="text-12px opacity-90">消息</text>
          </view>
          <view class="flex items-center gap-1" @click="openScan">
            <wd-icon name="scan" size="14px" color="white" />
            <text class="text-12px opacity-90">扫一扫</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 搜索栏 -->
    <view class="bg-gradient-to-r from-blue-500 to-purple-600 px-4 pb-4">
      <view class="flex items-center gap-3">
        <view class="flex-1 flex items-center bg-white rounded-full px-4 py-3 gap-3 shadow-lg">
          <wd-icon name="search" size="18px" color="#666" />
          <input
            v-model="searchKeyword"
            class="flex-1 border-none outline-none bg-transparent text-15px text-gray-800"
            placeholder="搜索你想要的商品"
            @confirm="goToSearch"
          />
          <view class="w-1px h-4 bg-gray-200"></view>
          <wd-icon name="camera" size="16px" color="#999" />
        </view>
        <view class="w-10 h-10 bg-white/20 rounded-full flex items-center justify-center" @click="goToSearch">
          <wd-icon name="search" size="18px" color="white" />
        </view>
      </view>
    </view>

    <!-- 轮播图 -->
    <view class="px-4 -mt-2 mb-4">
      <view class="bg-white rounded-3xl p-3 shadow-lg">
        <wd-swiper
          :list="banners.map((b: Banner) => b.image)"
          :autoplay="true"
          :interval="4000"
          :indicator-dots="true"
          height="200px"
          border-radius="16px"
        />
      </view>
    </view>

    <!-- 快捷功能入口 -->
    <view class="px-4 mb-4">
      <view class="bg-white rounded-3xl p-4 shadow-lg">
        <view class="grid grid-cols-5 gap-4">
          <view class="flex flex-col items-center gap-2" @click="navigateTo('/subPackages/game-package/list/index')">
            <view class="w-12 h-12 bg-gradient-to-br from-red-400 to-pink-500 rounded-2xl flex items-center justify-center">
              <wd-icon name="gift" size="24px" color="white" />
            </view>
            <text class="text-11px text-gray-600 text-center">游戏中心</text>
          </view>
          <view class="flex flex-col items-center gap-2" @click="navigateTo('/subPackages/user-package/coupon/index')">
            <view class="w-12 h-12 bg-gradient-to-br from-orange-400 to-red-500 rounded-2xl flex items-center justify-center">
              <wd-icon name="coupon" size="24px" color="white" />
            </view>
            <text class="text-11px text-gray-600 text-center">领券中心</text>
          </view>
          <view class="flex flex-col items-center gap-2" @click="goToFlashSale">
            <view class="w-12 h-12 bg-gradient-to-br from-green-400 to-blue-500 rounded-2xl flex items-center justify-center">
              <wd-icon name="flash" size="24px" color="white" />
            </view>
            <text class="text-11px text-gray-600 text-center">限时抢购</text>
          </view>
          <view class="flex flex-col items-center gap-2" @click="goToVipCenter">
            <view class="w-12 h-12 bg-gradient-to-br from-purple-400 to-pink-500 rounded-2xl flex items-center justify-center">
              <wd-icon name="crown" size="24px" color="white" />
            </view>
            <text class="text-11px text-gray-600 text-center">会员专享</text>
          </view>
          <view class="flex flex-col items-center gap-2" @click="goToPointsMall">
            <view class="w-12 h-12 bg-gradient-to-br from-yellow-400 to-orange-500 rounded-2xl flex items-center justify-center">
              <wd-icon name="star" size="24px" color="white" />
            </view>
            <text class="text-11px text-gray-600 text-center">积分商城</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 特色活动区域 -->
    <view class="px-4 mb-4">
      <view class="bg-gradient-to-r from-red-500 to-pink-500 rounded-3xl p-4 text-white shadow-lg">
        <view class="flex items-center justify-between">
          <view>
            <text class="text-18px font-bold block mb-1">🎉 新人专享</text>
            <text class="text-13px opacity-90">注册即送188元大礼包</text>
          </view>
          <view class="bg-white/20 px-4 py-2 rounded-full">
            <text class="text-13px font-medium">立即领取</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 商品分类 -->
    <view class="px-4 mb-4">
      <view class="bg-white rounded-3xl p-4 shadow-lg">
        <view class="flex items-center justify-between mb-3">
          <text class="text-16px font-bold text-gray-800">商品分类</text>
          <view class="flex items-center gap-1">
            <text class="text-12px text-gray-500">全部</text>
            <wd-icon name="arrow-right" size="12px" color="#999" />
          </view>
        </view>
        <view class="grid grid-cols-4 gap-4">
          <view
            v-for="category in categories.slice(0, 8)"
            :key="category.id"
            class="flex flex-col items-center gap-2 p-2"
            @click="goToCategory(category.id)"
          >
            <view class="w-12 h-12 bg-gradient-to-br from-blue-100 to-purple-100 rounded-2xl flex items-center justify-center">
              <wd-icon :name="category.icon || 'category'" size="22px" color="#6366f1" />
            </view>
            <text class="text-11px text-gray-600 text-center leading-tight">{{ category.name }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 今日推荐 -->
    <view class="px-4 mb-4">
      <view class="bg-white rounded-3xl shadow-lg overflow-hidden">
        <view class="bg-gradient-to-r from-yellow-400 to-orange-500 px-4 py-3 text-white">
          <view class="flex items-center justify-between">
            <view class="flex items-center gap-2">
              <text class="text-16px font-bold">⚡ 今日推荐</text>
              <view class="bg-white/20 px-2 py-1 rounded-full">
                <text class="text-10px">HOT</text>
              </view>
            </view>
            <text class="text-12px opacity-90">更多好物 ></text>
          </view>
        </view>
        
        <view class="p-4">
          <view class="grid grid-cols-2 gap-3">
            <view
              v-for="product in hotProducts"
              :key="product.id"
              class="relative bg-gray-50 rounded-2xl overflow-hidden border border-gray-100"
              @click="goToProductDetail(product.id)"
            >
              <image :src="product.images[0]" class="w-full h-32 bg-white" mode="aspectFit" />
              
              <view class="p-3">
                <text class="text-14px font-600 text-gray-800 mb-1 line-clamp-2 leading-tight">{{ product.name }}</text>
                <text class="text-11px text-gray-500 mb-2 line-clamp-1">{{ product.description }}</text>
                
                <view class="flex items-center justify-between">
                  <view>
                    <text class="text-16px font-700 text-red-500">{{ formatPrice(product.defaultPrice) }}</text>
                    <text v-if="product.originalPrice && product.originalPrice > product.defaultPrice" class="text-11px text-gray-400 line-through block">
                      {{ formatPrice(product.originalPrice) }}
                    </text>
                  </view>
                  <view class="w-8 h-8 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full flex items-center justify-center shadow-md" @click.stop="addToCart(product)">
                    <wd-icon name="cart" size="14px" color="#fff" />
                  </view>
                </view>
              </view>
              
              <!-- 折扣标签 -->
              <view v-if="product.originalPrice && product.originalPrice > product.defaultPrice" class="absolute top-2 left-2 bg-red-500 text-white px-2 py-1 rounded-full">
                <text class="text-10px font-bold">{{ Math.round((1 - product.defaultPrice / product.originalPrice) * 100) }}%OFF</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 限时抢购 -->
    <view class="px-4 mb-4">
      <view class="bg-white rounded-3xl shadow-lg overflow-hidden">
        <view class="bg-gradient-to-r from-red-500 to-pink-500 px-4 py-3 text-white">
          <view class="flex items-center justify-between">
            <view class="flex items-center gap-2">
              <text class="text-16px font-bold">🔥 限时抢购</text>
              <view class="bg-white/20 px-2 py-1 rounded-full">
                <text class="text-10px">23:59:42</text>
              </view>
            </view>
            <text class="text-12px opacity-90">更多秒杀 ></text>
          </view>
        </view>
        
        <view class="p-4">
          <scroll-view scroll-x class="whitespace-nowrap">
            <view class="flex gap-3">
              <view 
                v-for="product in flashSaleProducts" 
                :key="product.id" 
                class="inline-block w-32 bg-gray-50 rounded-2xl overflow-hidden border border-gray-100 flex-shrink-0"
                @click="goToProductDetail(product.id)"
              >
                <image :src="product.image" class="w-full h-24 bg-white" mode="aspectFit" />
                <view class="p-2">
                  <text class="text-12px text-gray-600 line-clamp-1 mb-1">{{ product.name }}</text>
                  <view class="flex items-center gap-1">
                    <text class="text-14px font-700 text-red-500">{{ formatPrice(product.currentPrice) }}</text>
                    <text class="text-10px text-gray-400 line-through">{{ formatPrice(product.originalPrice) }}</text>
                  </view>
                  <view class="bg-red-100 text-red-600 text-10px px-1 py-0.5 rounded mt-1 text-center">
                    <text>{{ product.discount }}%OFF</text>
                  </view>
                </view>
              </view>
            </view>
          </scroll-view>
        </view>
      </view>
    </view>

    <!-- 猜你喜欢 -->
    <view class="px-4 mb-4">
      <view class="bg-white rounded-3xl shadow-lg">
        <view class="px-4 py-3 border-b border-gray-100">
          <text class="text-16px font-bold text-gray-800">💝 猜你喜欢</text>
        </view>
        
        <view class="p-4">
          <view class="grid grid-cols-2 gap-3">
            <view 
              v-for="product in recommendProducts.slice(0, 6)" 
              :key="product.id" 
              class="bg-gray-50 rounded-2xl overflow-hidden border border-gray-100"
              @click="goToProductDetail(product.id)"
            >
              <image :src="product.images[0]" class="w-full h-32 bg-white" mode="aspectFit" />
              <view class="p-3">
                <text class="text-13px text-gray-800 mb-1 line-clamp-2 leading-tight">{{ product.name }}</text>
                <text class="text-11px text-gray-500 mb-2 line-clamp-1">{{ product.description }}</text>
                <view class="flex items-center justify-between">
                  <text class="text-15px font-700 text-red-500">{{ formatPrice(product.defaultPrice) }}</text>
                  <view class="flex items-center gap-1">
                    <wd-icon name="star-on" size="10px" color="#fbbf24" />
                    <text class="text-10px text-gray-500">{{ product.rating }}</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部间距 -->
    <view class="h-25" />
  </view>
</template>



<route lang="json">
{
  "name": "index",
  "layout": "tabbar",
  "style": {
    "navigationBarTitleText": "首页"
  }
}
</route>
